<template>
    <div class="User-container content-wrapper">

        <div class="filter-wrapper">
            <el-form ref="filterForm" :model="listQuery" :inline="true">

                <el-form-item size="medium">
                    <el-select v-model="listQuery.ossName" placeholder="OSS供应商" style="width: 200px" @change="handleOssSelectChange">
                        <el-option
                                v-for="item in ossNameOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item size="medium">
                    <el-select v-model="listQuery.bucketName" placeholder="空间名称"
                               @change="handleBucketSelectChange"
                               style="width: 200px"
                    >
                        <el-option
                                v-for="item in bucketOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item size="medium">
                    <el-select v-model="listQuery.status" placeholder="状态" style="width: 100px">
                        <el-option
                                v-for="item in statusOptions"
                                :key="item.key"
                                :label="item.label"
                                :value="item.key">
                        </el-option>
                    </el-select>
                </el-form-item>

                <el-form-item prop="fname" size="medium">
                    <el-input v-model="listQuery.fname" placeholder="文件名"></el-input>
                </el-form-item>

                <el-button type="primary" size="medium" icon="el-icon-search" @click="handleFilter">搜索</el-button>
                <el-button type="primary" size="medium" icon="el-icon-mars-reset" @click="handleResetFilter">重置</el-button>
                <el-button type="danger" size="medium" icon="el-icon-delete" @click="handleBatchDelete">删除</el-button>
                <el-button type="primary" size="medium" icon="el-icon-upload" @click="handleUpload">上传</el-button>
            </el-form>

        </div>

        <el-table
                :data="list"
                border fit
                highlight-current-row
                v-loading="listLoading"
                element-loading-text="给我一点时间"
                @selection-change="handleSelectionChange">

            <el-table-column
                    type="selection"
                    width="55" align="center">
            </el-table-column>
            <el-table-column type="index" width="55" align="center"></el-table-column>

            <el-table-column label="文件名" align="left">
                <template slot-scope="scope">
                    <a :href="scope.row.url" target="_blank" style="color:#409EFF">{{scope.row.fname}}</a>
                </template>
            </el-table-column>

            <el-table-column label="文件大小" width="200px" align="center">
                <template slot-scope="scope"> {{scope.row.fsize | formatSize}} </template>
            </el-table-column>

            <el-table-column label="文件类型" width="200px" align="center">
                <template slot-scope="scope"> {{scope.row.ftype}} </template>
            </el-table-column>

            <el-table-column label="上传时间" width="180px" align="center">
                <template slot-scope="scope"> {{scope.row.uploadTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}} </template>
            </el-table-column>

            <el-table-column label="备注" width="200px" align="center">
                <template slot-scope="scope"> {{scope.row.remarks}} </template>
            </el-table-column>

            <el-table-column label="操作" width="280px" align="center">
                <template slot-scope="scope">
                    <el-popover
                            ref="popover1"
                            placement="left-start"
                            :title="fileDetail.fname"
                            width="350"
                            height="450"
                            trigger="click"
                            @show="showPopover(scope.row)">
                        <div class="fileDetail">
                            <div class="file_pic">
                                <img :src="fileDetail.url" alt="">
                            </div>
                            <p>
                                <span style="font-weight: bold">文件大小：</span>
                                <span>{{fileDetail.fsize | formatSize}}</span>
                            </p>
                            <p>
                                <span style="font-weight: bold">最后更新：</span>
                                <span>{{fileDetail.uploadTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}')}}</span>
                            </p>
                            <div>
                                <div style="float:left;font-weight: bold">外链地址：</div>
                                <div style="float:left;width: 250px; word-wrap:break-word">
                                    <a :href="fileDetail.url" target="_blank">{{fileDetail.url}}</a>
                                </div>
                            </div>

                        </div>
                    </el-popover>
                    <el-button v-popover:popover1 size="small" type="primary" icon="el-icon-view" ></el-button>
                    <el-button size="small" type="danger" icon="delete" @click="handleDelete(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div v-show="!listLoading" class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="listQuery.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="listQuery.rows"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="dialogTitle" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :close-on-press-escape="false" @close="handleDialogClose">

            <el-form :model="uploadForm" :inline="true">
                <el-form-item size="medium">
                    <el-input v-model="uploadForm.prefixName" placeholder="文件名前缀"></el-input>
                </el-form-item>
            </el-form>

            <div class="upload-container">
                <div class="drop-box">
                    <h4 style="">点击，或将文件拖拽到这里上传</h4>
                    <label for="file">
                        <i class="el-icon-picture"></i>
                    </label>
                </div>

                <file-upload
                        :post-action="uploadAction"
                        :extensions="extensions"
                        :accept="accept"
                        :multiple="true"
                        :size="size || 0"
                        :thread="thread < 1 ? 1 : (thread > 5 ? 5 : thread)"
                        :headers="headers"
                        :drop="true"
                        :drop-directory="true"
                        v-model="files"
                        @input-filter="inputFilter"
                        @input-file="inputFile"
                        ref="upload">
                </file-upload>
            </div>

            <div class="preview">
                <el-table
                        :data="files"
                        border fit
                        highlight-current-row
                        v-loading="listLoading">

                    <el-table-column type="index" width="55" align="center">#</el-table-column>

                    <el-table-column label="图片预览" width="120" align="center">
                        <template slot-scope="scope">
                            <img v-if="scope.row.thumb" :src="scope.row.thumb" width="40" height="auto" />
                        </template>
                    </el-table-column>

                    <el-table-column label="文件名称" align="left">
                        <template slot-scope="scope">
                            {{scope.row.name}}
                            <el-progress
                                    v-if="scope.row.active || scope.row.progress !== '0.00'"
                                    :text-inside="true"
                                    :stroke-width="18"
                                    :percentage="parseInt(scope.row.progress)">
                            </el-progress>
                        </template>
                    </el-table-column>
                    <el-table-column label="文件大小" width="120" align="center">
                        <template slot-scope="scope"> {{scope.row.size | formatSize}} </template>
                    </el-table-column>
                    <el-table-column label="已上传" width="120" align="center">
                        <template slot-scope="scope"> {{scope.row.speed | formatSize}} </template>
                    </el-table-column>
                    <el-table-column label="状态" width="80" align="center">
                        <template slot-scope="scope">
                            <span v-if="scope.row.error" style="color: #FA5555">{{scope.row.error}}</span>
                            <span v-else-if="scope.row.success" style="color: #67C23A">成功</span>
                            <span v-else-if="scope.row.active" style="color: #409EFF">上传中</span>
                            <span v-else></span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="250" align="center">
                        <template slot-scope="scope">
                            <el-button type="danger" size="small"
                                       @click.prevent="$refs.upload.remove(scope.row)"
                            >删除</el-button>
                            <el-button type="warning" size="small"
                                       :disabled="!scope.row.active"
                                       @click.prevent="scope.row.active ? $refs.upload.update(scope.row, {error: 'cancel'}) : false"
                            >取消</el-button>
                            <el-button type="primary" size="small"
                                       @click.prevent="$refs.upload.update(scope.row,{active: true, error: '', progress: '0.00'})"
                            >重新上传</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" icon="el-icon-upload"
                           :disabled="(!$refs.upload || !$refs.upload.active ? false : true)"
                           @click.prevent="$refs.upload.active = true">
                    上传文件
                </el-button>
            </span>
        </el-dialog>

    </div>
</template>

<script>
    import FileUpload from 'vue-upload-component'
    import ImageCompressor from 'image-compressor'

    import {
        deleted, deletedBatch, selectOne, selectList,
        uploadAction, getBuckets
    } from '@/api/system/oss'

    const ossNameOptions = [{label: '七牛云', key: 'qiniuyun'}, {label: '阿里云', key: 'aliyun'}]
    const statusOptions = [{label: '正常', key: 1}, {label: '禁止', key: 2}]

    export default {
        name: 'Oss',
        components: {
            FileUpload
        },
        data() {
            return {
                list: [],
                total: null,
                listLoading: false,
                multipleSelection: [],
                listQuery: {
                    page: 1,
                    rows: 10,
                    ossName: 'qiniuyun',
                    bucketName: undefined,
                    fname: undefined,
                    status: 1
                },
                ossNameOptions,
                statusOptions,
                bucketOptions: [],

                dialogFormVisible: false,
                dialogTitle: '',
                fileDetail: {
                    fname: '',
                    fsize: '',
                    ftype: '',
                    url: '',
                    uploadTime: ''
                },

                files: [],
                uploadAuto: false,
                uploadAction: uploadAction,
                autoCompress: 1024 * 1024 * 10,
                size: 1024 * 1024 * 10,
                thread: 3,
                accept: 'image/png,image/gif,image/jpeg,image/webp',
                extensions: 'gif,jpg,jpeg,png,webp',
                headers: {
                    'X-Token': 'xxxx',
                },
                uploadForm: {
                    ossName: null,
                    bucketName: null,
                    prefixName: null,
                    remark: '未知'
                }
            }
        },
        created() {
            this.getOssBuckets()
        },
        methods: {
            getOssName() {
                let ossName = ossNameOptions.find((value, index, arr) => {
                    return value.key == this.listQuery.ossName
                })
                return ossName.label
            },
            handleUpload() {//添加数据窗口
                this.dialogFormVisible = true
            },
            handleFilter() {//条件过滤
                this.listQuery.page = 1
                this.getTableData()
            },
            handleResetFilter() {//重置过滤条件
                this.$refs.filterForm.resetFields()
                this.getTableData()
            },
            handleSelectionChange(val) {//多选
                this.multipleSelection = val;
            },
            handleSizeChange(val) {
                this.listQuery.rows = val
                this.getTableData()
            },
            handleCurrentChange(val) {
                this.listQuery.page = val
                this.getTableData()
            },

            handleDelete(row) {//删除数据
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    deleted(row.id).then(response => {
                        if(response.data.status) {
                            this.$notify({
                                title: '成功', message: response.data.message,
                                type: 'success', duration: 2000
                            })
                            this.getTableData()
                        } else {
                            this.$notify({
                                title: '发生错误', message: response.data.message,
                                type: 'error', duration: 2000
                            })
                        }
                    })
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            handleBatchDelete() {//批量删除数据
                this.$confirm('确定要删除？', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    if(this.multipleSelection.length > 0) {
                        let ids = []
                        for(let item of this.multipleSelection) {
                            ids.push(item.id)
                        }
                        deletedBatch({ids: ids.join(',')}).then(response => {
                            if(response.data.status) {
                                this.$notify({
                                    title: '成功', message: response.data.message,
                                    type: 'success', duration: 2000
                                })
                                this.getTableData()
                            } else {
                                this.$notify({
                                    title: '发生错误', message: response.data.message,
                                    type: 'error', duration: 2000
                                })
                            }
                        })

                    } else {
                        this.$notify({
                            title: '提示', message: '请选择需要删除的记录',
                            type: 'warning', duration: 2000
                        })
                    }
                }).catch(() => {
                    this.$message({ type: 'info', message: '已取消删除' })
                })
            },
            getTableData() {
                this.listLoading = true
                selectList(this.listQuery).then(response => {
                    this.list = response.data.list
                    this.total = response.data.total
                    this.listLoading = false
                }).catch(error => {
                    console.log(error)
                    this.listLoading = false
                })
            },

            handleOssSelectChange() { //OSS供应商变更，
                //加载对应的空间列表
                this.getOssBuckets()
            },
            handleBucketSelectChange() {//供应商变更
                //加载对应空间下的数据列表
                this.getTableData()
            },
            handleDialogClose() {//关闭窗口回调函数
                this.files = []
                this.getTableData()
            },
            getOssBuckets() {
                this.bucketOptions = []
                getBuckets({'ossName': this.listQuery.ossName}).then(response => {
                    for(let item of response.data) {
                        this.bucketOptions.push({'label': item, 'key': item})
                    }
                    this.listQuery.bucketName = response.data[0]

                    this.dialogTitle = 'OSS供应商 [ '+this.getOssName()+' ] - 存储空间 [ '+response.data[0]+' ]'
                    this.getTableData()
                }).catch(error => {
                    console.log(error)
                })
            },
            showPopover(row) {
                this.fileDetail.fname = row.fname
                this.fileDetail.url = row.url
                this.fileDetail.fsize = row.fsize
                this.fileDetail.mimeType = row.ftype
                this.fileDetail.uploadTime = row.uploadTime
            },
            resetForm() {//重置表单
                this.$refs['form'].resetFields()
            },

            inputFilter(newFile, oldFile, prevent) {
                if (newFile && !oldFile) {
                    // 添加文件前
                    // 过滤系统文件 和隐藏文件
                    if (/(\/|^)(Thumbs\.db|desktop\.ini|\..+)$/.test(newFile.name)) {
                        return prevent()
                    }
                    // 过滤 php html js 文件
                    if (/\.(php5?|html?|jsx?)$/i.test(newFile.name)) {
                        return prevent()
                    }

                    // 自动压缩
                    if (newFile.file && newFile.type.substr(0, 6) === 'image/' && this.autoCompress > 0 && this.autoCompress < newFile.size) {
                        newFile.error = 'compressing'
                        const imageCompressor = new ImageCompressor(null, {
                            convertSize: Infinity,
                            maxWidth: 512,
                            maxHeight: 512,
                        })
                        imageCompressor.compress(newFile.file)
                            .then((file) => {
                                this.$refs.upload.update(newFile, { error: '', file, size: file.size, type: file.type })
                            })
                            .catch((err) => {
                                this.$refs.upload.update(newFile, { error: err.message || 'compress' })
                            })
                    }

                    if (newFile && (!oldFile || newFile.file !== oldFile.file)) {
                        // 创建 blob 字段
                        newFile.blob = ''
                        let URL = window.URL || window.webkitURL
                        if (URL && URL.createObjectURL) {
                            newFile.blob = URL.createObjectURL(newFile.file)
                        }
                        // 缩略图
                        newFile.thumb = ''
                        if (newFile.blob && newFile.type.substr(0, 6) === 'image/') {
                            newFile.thumb = newFile.blob
                        }
                    }
                }
            },
            inputFile(newFile, oldFile) {
                if (newFile && !oldFile) {
                    // 添加文件
                }

                if (newFile && oldFile) {
                    // 更新文件

                    // 开始上传
                    if (newFile.active && !oldFile.active) {
                        // beforeSend
                        //设置每个文件携带的参数
                        this.uploadForm.ossName = this.listQuery.ossName
                        this.uploadForm.bucketName = this.listQuery.bucketName
                        newFile.data = Object.assign({}, this.uploadForm)

                        // 限定最小字节
                        if (newFile.size >= 0 && this.minSize > 0 && newFile.size < this.minSize) {
                            this.$refs.upload.update(newFile, { error: 'size' })
                        }
                    }
                    // 上传进度
                    if (newFile.progress !== oldFile.progress) {
                        //console.log('progress', newFile.progress, newFile)
                    }
                    // 上传错误
                    if (newFile.error !== oldFile.error) {
                        //console.log('error', newFile.error, newFile)
                    }
                    // 上传成功
                    if (newFile.success !== oldFile.success) {
                        //console.log('success', newFile.success, newFile)
                    }
                }

                if (!newFile && oldFile) {
                    // 删除文件
                    // 自动删除 服务器上的文件
                    if (oldFile.success && oldFile.response.id) {
                        // $.ajax({
                        //   type: 'DELETE',
                        //   url: '/file/delete?id=' + oldFile.response.id,
                        // });
                    }
                }

                // 自动上传
                if (Boolean(newFile) !== Boolean(oldFile) || oldFile.error !== newFile.error) {
                    if (this.uploadAuto && !this.$refs.upload.active) {
                        this.$refs.upload.active = true
                    }
                }
            },
        }
    }
</script>

<!-- 局部样式 -->
<style rel="stylesheet/scss" lang="scss" scoped>
    .fileDetail{
        .file_pic{
            width: 100%; height: 200px;text-align: center;
            img{
                vertical-align: middle;
                max-width: 100%;
                max-height: 100%;
            }
        }
        a{
            color: #409EFF
        }
    }

    .upload-container {
        width: 100%;
        .file-uploads{
            display: none;
        }
        .drop-box {
            border: 5px dashed gainsboro;
            text-align: center;
            position: relative;
            height: 200px;
            &:hover{
                border: 5px dashed gainsboro;
                background: #EEEEEE;
            }

            h4 {
                cursor: pointer;
                margin-top: 50px;
            }
            label {
                cursor: pointer;
                display: inline-block;
                padding-top: 100px;
                position: absolute;
                box-sizing: border-box;
                top: 0px;
                bottom: 0px;
                left: 0px;
                right: 0px;
                color: #409EFF;
                i {
                    font-size: 56px;
                }


            }
        }
    }

    .preview {
        margin-top: 20px;
    }
</style>